package top.revery.task.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import top.revery.api.entity.task.BaseLogTask;
;
import top.revery.task.dto.LogTaskDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/14 14:35
 */
@Service
public class LogTaskService {
    @Autowired
    private LogTaskDto logTaskDto;
    public Page<BaseLogTask> findPage(int pageNum, int pageSize, Map map) {

        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "opT");
        Specification<BaseLogTask> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(order));
        return logTaskDto.findAll(specification, pageRequest);
    }

    private Specification<BaseLogTask> createSpecification(Map map) {

        return new Specification<BaseLogTask>() {
            @Override
            public Predicate toPredicate(Root<BaseLogTask> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //日期查询
                if (map.get("startTime") != null && !"".equals(map.get("startTime"))) {
                    predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.get("opT").as(String.class), (String) map.get("startTime")));
                }
                if (map.get("endTime") != null && !"".equals(map.get("endTime"))) {
                    predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("opT").as(String.class), (String) map.get("endTime")));
                }
                return predicate;
            }
        };
    }
}
